<?php
namespace Icsoc\MonitorBundle\Controller;

use Icsoc\CoreBundle\Controller\BaseController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

/**
 * 告警配置
 * Class AlarmController
 * @package Icsoc\MonitorBundle\Controller
 */
class AlarmController extends BaseController
{
    //告警字段翻译
    private $alarmText = array(
        'que_num' => '排队',
        'ring_num' => '振铃',
        'call_num' => '通话',
        'ready_num' => '整理',
        'arrange_num' => '就绪',
        'busy_num' => '置忙',
    );
    //告警提示类型
    private $alarmType = array(
        1 => '短信',
    );

    /**
     * 报警配置列表
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function indexAction()
    {
        return $this->render(
            'IcsocMonitorBundle:Alarm:index.html.twig'
        );
    }

    /**
     * 报警配置列表数据
     * @param Request $request
     * @return JsonResponse
     */
    public function listDataAction(Request $request)
    {
        $rows = $request->get('rows', 10);
        $page = $request->get('page', 1);
        $sidx = $request->get('sidx', 'id');
        $sord = $request->get('sord', 'ASC');
        $fliter = $request->get('fliter', '');

        $user = $this->getUser();
        $vccId = $user->getVccId();

        $fliter = json_decode($fliter, true)['keyword'];
        $where = " AND (alarm_name LIKE '%".$fliter."%' OR alarm_time LIKE '%".$fliter."%')";
        //$where = " vcc_id =? AND alarm_name LIKE '%".$fliter."%' OR alarm_value LIKE '%".$fliter."%'";
        $em = $this->getDoctrine()->getManager();
        //技能组
        $queues = $em->getRepository('IcsocSecurityBundle:WinQueue')
            ->getQuesName("q.vccId = :vccId AND q.isDel = 0", array('vccId' => $vccId));
        $conn = $this->get("doctrine.dbal.default_connection");
        $total = $conn->fetchColumn("SELECT count(*) FROM cc_monitor_alarm WHERE vcc_id=:vcc_id $where", array('vcc_id' => $vccId));
        $data = $conn->fetchAll(
            "SELECT id,alarm_name,alarm_time,que_num,ring_num,call_num,ready_num,arrange_num,busy_num,alarm_type,alarm_value,que_config FROM cc_monitor_alarm WHERE vcc_id=:vcc_id $where  ORDER BY ".$sidx.' '.$sord." limit ".($page*$rows-$rows).",".$rows,
            array('vcc_id' => $vccId)
        );
        $row = array();
        foreach ($data as $val) {
            $child = array();
            $child['id'] = $val['id'];
            $child['alarm_name'] = $val['alarm_name'];
            $child['alarm_time'] = $val['alarm_time'];
            $child['alarm_type'] = $this->alarmType[$val['alarm_type']];
            if (!empty($val['alarm_value'])) {
                $arr = json_decode($val['alarm_value']);
                $str = '';
                foreach ($arr as $vl) {
                    $str .= $vl.'<br>';
                }
                $child['alarm_value'] = rtrim($str, '<br>');
            }
            $child['que_config'] = '';
            if (!empty($val['que_config'])) {
                $arr = json_decode($val['que_config'], true);
                foreach ($arr as $vl) {
                    if (!empty($queues[$vl])) {
                        $child['que_config'] .= $queues[$vl].',';
                    }
                }
                $child['que_config'] = rtrim($child['que_config'], ',');
            }
            $child['que_config'] = empty($child['que_config']) ? '所有技能组' : $child['que_config'];
            $term = '';
            foreach ($val as $ky => $vl) {
                if (preg_match("/_num/", $ky)) {
                    if (!empty($vl)) {
                        $arr = json_decode($vl);
                        foreach ($arr as $v) {
                            $term .= $this->alarmText[$ky].' '.$v.'<br>';
                        }
                    }
                }
            }
            $child['term'] = rtrim($term, '<br>');
            $row[] = $child;
        }
        $result = array(
            'rows' => $row,
            'total' => ceil($total/$rows),
            'page' => $page,
            'records' => $total,
        );

        return new JsonResponse($result);
    }

    /**
     * 报警配置页面
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function htmlAlarmAction(Request $request)
    {
        $id = $request->get('id', 0);
        $user = $this->getUser();
        $vccId = $user->getVccId();
        $conn = $this->get("doctrine.dbal.default_connection");
        $data = $conn->fetchAssoc(
            "SELECT alarm_name,alarm_time,que_num,ring_num,call_num,ready_num,arrange_num,busy_num,alarm_type,alarm_value,que_config FROM cc_monitor_alarm WHERE id=? AND vcc_id=?",
            array($id, $vccId)
        );
        $result = array();
        if (!empty($data)) {
            foreach ($data as $key => $val) {
                switch ($key) {
                    case 'alarm_type':
                        if (empty($val)) {
                            $val = 1;
                        }
                        $result[$key] = $val;
                        break;
                    case 'alarm_name':
                        $result[$key] = $val;
                        break;
                    case 'alarm_time':
                        $result[$key] = $val;
                        break;
                    case 'enable_alarm':
                        $result[$key] = json_decode($val);
                        break;
                    case 'alarm_value':
                        if (!empty($val)) {
                            $arr = json_decode($val);
                            $str = '';
                            foreach ($arr as $vl) {
                                $str .= $vl.'\n';
                            }
                            $result[$key] = rtrim($str, '\n');
                        } else {
                            $result[$key] = '';
                        }
                        break;
                    case 'que_config':
                        $result[$key] = json_decode($val);
                        break;
                    default:
                        if (!empty($val)) {
                            $arr = json_decode($val);
                            foreach ($arr as $vl) {
                                $arr2 = explode(' ', $vl);
                                $arr3['name'] = $key;
                                $arr3['compare'] = $arr2[0];
                                $arr3['number'] = $arr2[1];
                                $result['list'][] = $arr3;
                            }
                            $result['list_num'] = count($result['list'])-1;
                        }
                        break;
                }
            }
        } else {
            $result = array('alarm_name' => '', 'que_config' => array(), 'alarm_time' => '', 'alarm_type' => 1, 'alarm_value' => '', 'list' => array());
        }
        $em = $this->getDoctrine()->getManager();
        //技能组
        $queues = $em->getRepository('IcsocSecurityBundle:WinQueue')
            ->getQuesName("q.vccId = :vccId AND q.isDel = 0", array('vccId' => $vccId));

        return $this->render(
            'IcsocMonitorBundle:Alarm:alarm.html.twig',
            array('result' => $result, 'queues' => $queues, 'id' => $id)
        );
    }

    /**
     * 保存配置
     * @param Request $request
     * @return JsonResponse
     */
    public function setAlarmAction(Request $request)
    {
        $name = $request->get('name', '');
        $compare = $request->get('compare', '');
        $number = $request->get('number', '');

        $alarmType = $request->get('alarm_type', '');
        $alarmValue = $request->get('alarm_value', '');
        $alarmName = $request->get('alarm_name', '');
        $queConfig = $request->get('que_config', '');
        $alarmTime = $request->get('alarm_time', '');
        $id = $request->get('id', 0);

        $user = $this->getUser();
        $vccId = $user->getVccId();

        try {
            $conn = $this->get("doctrine.dbal.default_connection");
            //验证重复名称
            $count = $conn->fetchColumn(
                "SELECT count(id) FROM cc_monitor_alarm WHERE vcc_id=? AND alarm_name=? AND id!=?",
                array($vccId, $alarmName, $id)
            );
            $text = empty($id) ? '继续添加' : '重新修改';

            if ($count > 0) {
                $message = '名称已经存在';
                $type = 'error';
                goto end;
            }

            $data = array();
            $enable = array();
            foreach ($name as $key => $val) {
                $data[$val][] = $compare[$key].' '.$number[$key];
                if (!in_array($val, $enable)) {
                    $enable[] = $val;
                }
            }
            $data['enable_alarm'] = $enable;

            $alarmValue = explode("\r\n", $alarmValue);
            foreach ($alarmValue as $key => $val) {
                if (!empty($val)) {
                    $data['alarm_value'][] = $val;
                }
            }
            $data['que_config'] = $queConfig;
            //全部json一下
            foreach ($data as $key => $val) {
                if (!empty($val)) {
                    $data[$key] = json_encode($val);
                }
            }
            $data['alarm_name'] = $alarmName;
            $data['alarm_type'] = $alarmType;
            $data['alarm_time'] = $alarmTime;


            if ($id != 0) {
                $data['que_num'] = empty($data['que_num']) ? 0 : $data['que_num'];
                $data['ring_num'] = empty($data['ring_num']) ? 0 : $data['ring_num'];
                $data['call_num'] = empty($data['call_num']) ? 0 : $data['call_num'];
                $data['ready_num'] = empty($data['ready_num']) ? 0 : $data['ready_num'];
                $data['arrange_num'] = empty($data['arrange_num']) ? 0 : $data['arrange_num'];
                $data['busy_num'] = empty($data['busy_num']) ? 0 : $data['busy_num'];
                $conn->update(
                    'cc_monitor_alarm',
                    $data,
                    array('vcc_id' => $vccId, 'id' => $id)
                );
            } else {
                $data['vcc_id'] = $vccId;
                $conn->insert('cc_monitor_alarm', $data);
            }

            $message = '配置成功';
            $type = 'success';
            end:
            $data = array(
                'data' => array(
                    'msg_detail' => $message,
                    'type' => $type,
                    'link' => array(
                        array('text' => $text, 'href' => $this->generateUrl('icsoc_monitor_alarm_html', array('id' => $id))),
                        array('text' => '返回列表', 'href' => $this->generateUrl('icsoc_monitor_alarm_index')),
                    ),
                ),
            );

            return $this->redirect($this->generateUrl('icsoc_ui_message', $data));
        } catch (\Exception $e) {
            $data = array(
                'data' => array(
                    'msg_detail' => '配制失败',
                    'type' => 'error',
                    'link' => array(
                        array('text' => '返回列表', 'href' => $this->generateUrl('icsoc_monitor_alarm_index')),
                    ),
                ),
            );

            return $this->redirect($this->generateUrl('icsoc_ui_message', $data));
        }
    }

    /**
     * 删除报警配置
     * @param Request $request
     * @return JsonResponse
     */
    public function delAlarmAction(Request $request)
    {
        $ids = $request->get('id', '');
        $user = $this->getUser();
        $vccId = $user->getVccId();

        if (empty($ids)) {
            return new JsonResponse(array('code' => 400, 'message' =>'参数不存在'));
        }
        try {
            $conn = $this->get("doctrine.dbal.default_connection");
            $conn->executeQuery(
                "DELETE FROM cc_monitor_alarm WHERE vcc_id=$vccId AND id IN($ids)"
            );

            return new JsonResponse(array('error' => 0, 'message' =>'删除成功'));
        } catch (\Exception $e) {
            return new JsonResponse(array('error' => 1, 'message' =>'删除失败'));
        }
    }
}